package base;

import java.util.ArrayList;

public class Game {
	private Engine engine;
	private Client owner;
	private ArrayList<Client> clients = new ArrayList<Client>();
	
	public void addClient(Client client) {
		if (this.getEngine().getBoard().getPlayers().size() > this.getClients().size()) {
			this.clients.add(client);
			Player player = this.getFirstFreePlayer();
			client.setPlayer(player);
			player.setClient(client);
		}
	}
	
	private Player getFirstFreePlayer() {
		Player freePlayer = null;
		
		for (Player player : this.getEngine().getBoard().getPlayers()) {
			if (!player.hasClient()) {
				freePlayer = player;
			}
		}
		
		return freePlayer;
	}

	public void removeClient(Client client) {
		this.clients.remove(client);
		
		for (Player player : this.getEngine().getBoard().getPlayers()) {
			if (player.getClient() == client) {
				player.setClient(null);
			}
		}
		
		client.clear();
	}
	
	ArrayList<Client> getClients() {
		return new ArrayList<Client>(this.clients);
	}

	public Engine getEngine() {
		return engine;
	}
	
	Client getOwner() {
		return this.owner;
	}
	
	public Game(Client owner, Engine engine) {
		this.owner = owner;
		this.engine = engine;
		
		this.addClient(owner);
	}
}
